package com.finger.forest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureCollection;
import com.esri.arcgisruntime.data.FeatureCollectionTable;
import com.esri.arcgisruntime.data.FeatureEditResult;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.FeatureSet;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureCollectionLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.mapping.view.SketchCreationMode;
import com.esri.arcgisruntime.mapping.view.SketchEditor;
import com.esri.arcgisruntime.mapping.view.SketchStyle;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.esri.arcgisruntime.symbology.TextSymbol;
import com.finger.forest.adapter.ConsultationAdapter;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.ToastUtils;
import com.google.android.material.snackbar.Snackbar;
import com.jakewharton.rxbinding2.view.RxView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * 同步会商
 */
public class ConsultationActivity extends BaseActivity {

    private static final String TAG = "ConsultationActivity";

    private MapView mMapView;

    private SimpleMarkerSymbol mPointSymbol;
    private SimpleLineSymbol mLineSymbol;
    private SimpleFillSymbol mFillSymbol;

    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.ivUpload)
    ImageView ivUpload;
    @BindView(R.id.rvSynchronization)
    RecyclerView rvSynchronization;

    @BindView(R.id.iv)
    ImageView iv;


    private ConsultationAdapter consultationAdapter;

    private List<Map<String,Object>> list = new ArrayList<>();

    //点集合
    private PointCollection mPointCollection = new PointCollection(SpatialReferences.getWebMercator());

    private List<Point> mPointList;

    /**
     * 按钮名称
     */
    String[] names = new String[]{
            "火点","消防车","消防员","火势箭头","移动箭头",
            "简单箭头","路障","描绘火情区域","飘旗","绘制围堰",
            "方形飘旗","三角旗","画圆","隔离带","输入文字",
            "绘制火线","绘制风向"};

    /**
     * 按钮图标
     */
    int[] icons = new int[]{
            R.mipmap.icon_fire_location,R.mipmap.icon_xiaofangche,R.mipmap.icon_xiaofangyuan,R.mipmap.icon_huoshijiantou,R.mipmap.icon_yidongfangxiang,
            R.mipmap.icon_jiandanjiantou,R.mipmap.icon_luzhang,R.mipmap.icon_huoqingquyu,R.mipmap.icon_piaoqi,R.mipmap.icon_huizhiweiya,
            R.mipmap.icon_fangxingpiaoqi,R.mipmap.icon_sanjiaoqi,R.mipmap.icon_huayuan,R.mipmap.icon_gelidai,R.mipmap.icon_shuruwenzi,
            R.mipmap.icon_huizhihuoxian,R.mipmap.icon_huizhifengxiang};

    /**
     * 地图图标
     */
    int[] mapIcons = new int[]{
            R.drawable.ic_fire,R.drawable.ic_xiaofangche,R.drawable.ic_xiaofangyuan,R.drawable.ic_fire,R.drawable.ic_fire,
            R.drawable.ic_fire,R.drawable.ic_luzhang,R.drawable.ic_fire,R.drawable.ic_piaoqi,R.drawable.ic_weiya,
            R.drawable.ic_fangqi,R.drawable.ic_sanjiaoqi,R.drawable.ic_fire,R.drawable.ic_gelidai,R.drawable.ic_fire,
            R.drawable.ic_fire_line,R.drawable.icon_wind};

    private int icon_position = -1;

    /**
     * 点图层
     */
    private ServiceFeatureTable mServiceFeatureTable;
    /**
     * 线图层
     */
    private ServiceFeatureTable mServiceFeatureTableLine;
    /**
     * 面图层
     */
    private ServiceFeatureTable mServiceFeatureTableArea;

    GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();

    private Callout mCallout;

    private SketchEditor mSketchEditor;

    @Override
    protected int setView() {
        return R.layout.activity_consultation;
    }

    @Override
    protected void receiveData() {
        for (int i=0;i<names.length;i++){
            Map<String,Object> mapTemp = new HashMap<>();
            mapTemp.put("name",names[i]);
            mapTemp.put("icon",icons[i]);
            list.add(mapTemp);
        }
    }

    @Override
    protected void initializeView() {
        // define symbols
        mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20);
        mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4);
        mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol);

        mMapView = findViewById(R.id.mapView);
        setupMap();

        consultationAdapter = new ConsultationAdapter(R.layout.consultation_item_view, list);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        rvSynchronization.setLayoutManager(gridLayoutManager);
        rvSynchronization.setAdapter(consultationAdapter);

        consultationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TextView itemTv = (TextView)view.findViewById(R.id.item_name);
                ToastUtils.show("选择"+itemTv.getText());
                //设置标识
                icon_position = position;
                //隐藏列表
                tag = 1;
                rotation();

                if (position==13 || position==15 || position==16){
                    //绘制自由线
                    mSketchEditor.start(SketchCreationMode.FREEHAND_LINE);
                } else if (position==3 || position==4 || position==5){
                    //绘制简单线
                    mSketchEditor.start(SketchCreationMode.POLYLINE);
                } else if (position==7){
                    //绘制面
                    mSketchEditor.start(SketchCreationMode.FREEHAND_POLYGON);
                } else if (position==12){
                    //绘制圆
                    drawCircle();
                } else if (position==14){
                    //绘制文字
                    drawPoint();
                } else {
                    //绘制点
                    mSketchEditor.start(SketchCreationMode.POINT);
                }

            }
        });

        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        rvSynchronization.measure(w, h);
        rlHeight = rvSynchronization.getMeasuredHeight();

        clicks();

        mGraphicsOverlay.setOpacity(0.5f);
        //画图标
        mMapView.getGraphicsOverlays().add(mGraphicsOverlay);

        // create a new sketch editor and add it to the map view
        mSketchEditor = new SketchEditor();
        mSketchEditor.setOpacity(0.5f);//设置透明度
        setSketchEditorStyle(mSketchEditor);//设置样式
        mMapView.setSketchEditor(mSketchEditor);

    }

    private void clicks() {
        //返回
        RxView.clicks(ivLeft).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> {
            finish();
        });
        //刷新
        RxView.clicks(ivRight).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> {
            //初始化加载同步会商数据
            initFeature();
        });
        //上传
        RxView.clicks(ivUpload).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> {
            upload();
        });

        RxView.clicks(iv).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> {
            rotation();
        });
    }

    private void upload() {
        if (icon_position == 12){
            //画圆上传GIS服务
            addFeature(new Polygon(mPointCollection), mServiceFeatureTableArea, null);
        } else {
            if (!mSketchEditor.isSketchValid()) {
                reportNotValid();
                mSketchEditor.stop();
                //resetButtons();
                return;
            }

            // get the geometry from sketch editor
            Geometry sketchGeometry = mSketchEditor.getGeometry();
            mSketchEditor.stop();
            //resetButtons();

            if (sketchGeometry != null) {

                // create a graphic from the sketch editor geometry
                Graphic graphic = new Graphic(sketchGeometry);
                String graphicStr = "";
                // assign a symbol based on geometry type
                if (graphic.getGeometry().getGeometryType() == GeometryType.POLYGON) {
                    graphic.setSymbol(mFillSymbol);
                    graphicStr = "面";

                    Polygon pg = (Polygon)graphic.getGeometry();
                    //上传到GIS服务
                    addFeature(pg, mServiceFeatureTableArea, null);
                } else if (graphic.getGeometry().getGeometryType() == GeometryType.POLYLINE) {
                    graphic.setSymbol(mLineSymbol);
                    graphicStr = "线";

                    Polyline pl = (Polyline)graphic.getGeometry();
                    //上传到GIS服务
                    addFeature(pl, mServiceFeatureTableLine, null);
                } else if (graphic.getGeometry().getGeometryType() == GeometryType.POINT ||
                        graphic.getGeometry().getGeometryType() == GeometryType.MULTIPOINT) {
                    graphic.setSymbol(mPointSymbol);
                    graphicStr = "点";

                    Point pt = (Point)graphic.getGeometry();
                    //上传到GIS服务
                    addFeature(pt, mServiceFeatureTable, null);
                }
                Log.i(TAG, graphicStr);
            }
        }
    }

    private void reportNotValid() {
        String validIf;
        if (mSketchEditor.getSketchCreationMode() == SketchCreationMode.POINT) {
            validIf = "Point only valid if it contains an x & y coordinate.";
        } else if (mSketchEditor.getSketchCreationMode() == SketchCreationMode.MULTIPOINT) {
            validIf = "Multipoint only valid if it contains at least one vertex.";
        } else if (mSketchEditor.getSketchCreationMode() == SketchCreationMode.POLYLINE
                || mSketchEditor.getSketchCreationMode() == SketchCreationMode.FREEHAND_LINE) {
            validIf = "Polyline only valid if it contains at least one part of 2 or more vertices.";
        } else if (mSketchEditor.getSketchCreationMode() == SketchCreationMode.POLYGON
                || mSketchEditor.getSketchCreationMode() == SketchCreationMode.FREEHAND_POLYGON) {
            validIf = "Polygon only valid if it contains at least one part of 3 or more vertices which form a closed ring.";
        } else {
            validIf = "No sketch creation mode selected.";
        }
        String report = "Sketch geometry invalid:\n" + validIf;
        Log.e(TAG, report);
    }

    @Override
    protected void loadDataFromServer() {

    }

    Point startPoint = null;


    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, SystemConfig.latitude, SystemConfig.longitude, SystemConfig.mapLevel);
            mMapView.setMap(map);

            // create service feature table from URL
            mServiceFeatureTable = new ServiceFeatureTable("http://192.168.1.187:6080/arcgis/rest/services/LY/syncConsultation/FeatureServer/0");
            mServiceFeatureTableLine = new ServiceFeatureTable("http://192.168.1.187:6080/arcgis/rest/services/LY/syncConsultation/FeatureServer/1");
            mServiceFeatureTableArea = new ServiceFeatureTable("http://192.168.1.187:6080/arcgis/rest/services/LY/syncConsultation/FeatureServer/2");

            //初始化加载同步会商数据
            initFeature();
        }
    }

    /**
     * 初始化加载同步会商数据
     */
    private void initFeature(){
        initFeatureCollectionLayer(-1);
        initFeatureCollectionLayerLine();
        initFeatureCollectionLayerArea();
    }


    /**
     * 初始化加载同步会商数据
     * @param position
     */
    private void initFeatureCollectionLayer(int position){
        if(position == -1){
            for (int i=0; i<mapIcons.length; i++){
                queryFeatureCollectionLayer(i);
            }
        } else{
            queryFeatureCollectionLayer(position);
        }
    }

    private void initFeatureCollectionLayerLine(){
        queryFeatureCollectionLayerLine(3);
        queryFeatureCollectionLayerLine(4);
        queryFeatureCollectionLayerLine(5);
        queryFeatureCollectionLayerLine(13);
        queryFeatureCollectionLayerLine(15);
        queryFeatureCollectionLayerLine(16);
    }

    private void initFeatureCollectionLayerArea(){
        queryFeatureCollectionLayerArea(7);
        queryFeatureCollectionLayerArea(12);
    }

    private void queryFeatureCollectionLayerLine(int position){
        //create query parameters
        QueryParameters queryParams = new QueryParameters();

        // 1=1 will give all the features from the table
        queryParams.setWhereClause("1=1 and type='icon"+ position +"'");

        //query feature from the table
        final ListenableFuture<FeatureQueryResult> queryResult = mServiceFeatureTableLine.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);

                SimpleRenderer renderer = null;
                if (position==3 ||position == 4 ||position == 5){
                    SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 2);
                    renderer = new SimpleRenderer(lineSymbol);
                } else{
                    BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(ConsultationActivity.this, mapIcons[position]);
                    PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
                    renderer = new SimpleRenderer(pms);
                }
                featureCollectionTable.setRenderer(renderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);

                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);


            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    private void queryFeatureCollectionLayerArea(int position){
        //create query parameters
        QueryParameters queryParams = new QueryParameters();

        // 1=1 will give all the features from the table
        queryParams.setWhereClause("1=1 and type='icon"+ position +"'");

        //query feature from the table
        final ListenableFuture<FeatureQueryResult> queryResult = mServiceFeatureTableArea.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);

                SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.NULL, Color.RED,
                        new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorRed), 2.0f));
                SimpleRenderer renderer = new SimpleRenderer(fillSymbol);
                featureCollectionTable.setRenderer(renderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);

                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);


            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    private void queryFeatureCollectionLayer(int position){
        //create query parameters
        QueryParameters queryParams = new QueryParameters();

        // 1=1 will give all the features from the table
        queryParams.setWhereClause("1=1 and type='icon"+ position +"'");

        //query feature from the table
        final ListenableFuture<FeatureQueryResult> queryResult = mServiceFeatureTable.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);

                SimpleRenderer renderer = null;
                if (position == 14){
                    Iterator<Feature> resultIterator = result.iterator();
                    while (resultIterator.hasNext()) {
                        // get the extent of the first feature in the result to zoom to
                        Feature feature = resultIterator.next();
                        Map<String, Object> attr = feature.getAttributes();
                        //查询文字标签
                        queryFeatureCollectionSecond(attr);
                    }

                } else{
                    BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(ConsultationActivity.this, mapIcons[position]);
                    PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
                    renderer = new SimpleRenderer(pms);

                    featureCollectionTable.setRenderer(renderer);

                    //create a feature collection from the above feature collection table
                    FeatureCollection featureCollection = new FeatureCollection();
                    featureCollection.getTables().add(featureCollectionTable);

                    //create a feature collection layer
                    FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);

                    //add the layer to the operational layers array
                    mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);
                }


            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    private void queryFeatureCollectionSecond(Map<String, Object> attr){
        String id = attr.get("OBJECTID").toString();
        String name = attr.get("name").toString();

        //create query parameters
        QueryParameters queryParams = new QueryParameters();

        // 1=1 will give all the features from the table
        queryParams.setWhereClause("OBJECTID='"+id+"' and type='icon14' and name='"+ name+"'");

        //query feature from the table
        final ListenableFuture<FeatureQueryResult> queryResult = mServiceFeatureTable.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);

                TextSymbol textSymbol = new TextSymbol(10, name, Color.RED, TextSymbol.HorizontalAlignment.CENTER, TextSymbol.VerticalAlignment.TOP);
                SimpleRenderer renderer = new SimpleRenderer(textSymbol);
                featureCollectionTable.setRenderer(renderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);


                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);


            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    private void addFeature(Geometry geometry, final ServiceFeatureTable featureTable, String name) {

        // create default attributes for the feature
        Map<String, Object> attributes = new HashMap<>();
        Log.i(TAG,""+icon_position);
        attributes.put("name", name==null? "name"+icon_position : name);
        attributes.put("type", "icon"+icon_position);

        // creates a new feature using default attributes and point
        Feature feature = null;
        if (geometry instanceof Polyline){
            Polyline pl = (Polyline)geometry;
            feature = featureTable.createFeature(attributes, pl);
        } else if (geometry instanceof Polygon){
            Polygon py = (Polygon)geometry;
            feature = featureTable.createFeature(attributes, py);
        } else if (geometry instanceof Point){
            Point p = (Point)geometry;
            feature = featureTable.createFeature(attributes, p);
        }

        // check if feature can be added to feature table
        if (featureTable.canAdd()) {
            // add the new feature to the feature table and to server
            featureTable.addFeatureAsync(feature).addDoneListener(() -> applyEdits(featureTable));
        } else {
            runOnUiThread(() -> logToUser(true, getString(R.string.error_cannot_add_to_feature_table)));
        }
    }

    private void applyEdits(ServiceFeatureTable featureTable) {

        // apply the changes to the server
        final ListenableFuture<List<FeatureEditResult>> editResult = featureTable.applyEditsAsync();
        editResult.addDoneListener(() -> {
            try {
                List<FeatureEditResult> editResults = editResult.get();
                // check if the server edit was successful
                if (editResults != null && !editResults.isEmpty()) {
                    if (!editResults.get(0).hasCompletedWithErrors()) {
                        runOnUiThread(() -> logToUser(false, getString(R.string.feature_added)));

                        //先清除
                        mGraphicsOverlay.getGraphics().clear();
                        //添加成功后，重新加载
                        queryFeatureCollectionLayer(icon_position);
                        queryFeatureCollectionLayerLine(icon_position);
                        queryFeatureCollectionLayerArea(icon_position);
                    } else {
                        throw editResults.get(0).getError();
                    }
                }
            } catch (InterruptedException | ExecutionException e) {
                runOnUiThread(() -> logToUser(true, getString(R.string.error_applying_edits, e.getCause().getMessage())));
            }
        });
    }

    private void logToUser(boolean isError, String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        if (isError) {
            Log.e(TAG, message);
        } else {
            Log.d(TAG, message);
        }
    }

    private int tag = 1;// 0是没有展开，1是展开的
    private ObjectAnimator animation;//旋转动画
    private float rlHeight;

    /**
     * 旋转逻辑
     */
    private void rotation() {
        ValueAnimator dropAnimator;
        Log.i(TAG, "tag："+tag);
        if (tag == 0) {// 展开逻辑
            Log.i(TAG, "展开逻辑");
            //animation = ObjectAnimator.ofFloat(iv, "rotation", 0, 180);
            iv.setImageDrawable(getResources().getDrawable(R.mipmap.xiala1));
            dropAnimator = createDropAnimator(rvSynchronization, 0, (int) rlHeight);
            rvSynchronization.setVisibility(View.VISIBLE);
            tag = 1;
        } else {
            Log.i(TAG, "收起逻辑");
            //animation = ObjectAnimator.ofFloat(iv, "rotation", 180, 0);
            iv.setImageDrawable(getResources().getDrawable(R.mipmap.xiala2));
            dropAnimator = createDropAnimator(rvSynchronization, (int) rlHeight, 0);
            dropAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    rvSynchronization.setVisibility(View.GONE);
                }
            });
            tag = 0;
        }
//        animation.setDuration(300);//设置动画持续时间
//        animation.start();
        dropAnimator.setDuration(1000);
        dropAnimator.start();
    }

    private ValueAnimator createDropAnimator(final View v, int start, int end) {
        ValueAnimator animator = ValueAnimator.ofInt(start, end);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator arg0) {
                int value = (int) arg0.getAnimatedValue();
                ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
                layoutParams.height = value;
                v.setLayoutParams(layoutParams);
            }
        });
        return animator;
    }

    @Override
    public void onPause() {
        super.onPause();
        // pause MapView
        mMapView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // resume MapView
        mMapView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // dispose MapView
        mMapView.dispose();
    }

    private void setSketchEditorStyle(SketchEditor editor){
        SketchStyle style = editor.getSketchStyle();//这里一定是从editor里get出来的style，否则修改无效果。
        SimpleMarkerSymbol marker = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 6);
        SimpleLineSymbol line = new SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.YELLOW, 2);
        SimpleLineSymbol feedLine = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 2);
        SimpleMarkerSymbol midMarker = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.TRANSPARENT, 0);
        SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.parseColor("#66FF0000"), line);
        SimpleFillSymbol feedFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.parseColor("#66FF0000"), feedLine);//透明度为40%的红色


        style.setSelectedVertexSymbol(marker);//操作时点的样式
        style.setMidVertexSymbol(midMarker);//画线或面时，线中间的点样式

        //手绘时显示的样式
        style.setVertexSymbol(marker);
        style.setLineSymbol(line);
        style.setFillSymbol(fillSymbol);

        //SketchEditor对象在Stop以后地图绘制的样式
        style.setFeedbackVertexSymbol(marker);
        style.setFeedbackLineSymbol(feedLine);
        style.setFeedbackFillSymbol(feedFillSymbol);
    }

    /**
     * 绘制点
     */
    private void drawPoint() {
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent event) {
                if (icon_position == -1){
                    ToastUtils.show("请选择标识");
                    return false;
                }
                // create a point from where the user clicked
                android.graphics.Point point = new android.graphics.Point((int) event.getX(), (int) event.getY());

                // create a map point from a point
                Point mapPoint = mMapView.screenToLocation(point);

                //判断类型：点、文字、线、面
                if (icon_position == 14){ //文字

                    View view = LayoutInflater.from(ConsultationActivity.this).inflate(R.layout.callout_edit,null);
                    TextView calloutCancelTv = (TextView)view.findViewById(R.id.tv_callout_cancel);
                    TextView calloutConfirmTv = (TextView)view.findViewById(R.id.tv_callout_confirm);
                    EditText inputEt = (EditText)view.findViewById(R.id.et_input);
                    calloutCancelTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mMapView.getCallout().dismiss();
                        }
                    });
                    calloutConfirmTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String name = inputEt.getText().toString();
                            addFeature(mapPoint, mServiceFeatureTable, name);
                            mMapView.getCallout().dismiss();
                        }
                    });

                    mCallout = mMapView.getCallout();
                    mCallout.setLocation(mapPoint);
                    mCallout.setContent(view);
                    Callout.Style style = new Callout.Style(ConsultationActivity.this, R.xml.callout_style_point);
                    mCallout.setStyle(style);
                    mCallout.show();
                } /*else { //点
                    // add a new feature to the service feature table
                    addFeature(mapPoint, mServiceFeatureTable, null);
                }*/

                return super.onSingleTapConfirmed(event);
            }

        });

    }

    /**
     * 绘制圆
     */
    private void drawCircle() {

        mPointList = new ArrayList<>();

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {

                double radius = 0;

                Point point = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));

                mPointList.add(point);
                if (mPointList.size() == 2) {
                    double x = (mPointList.get(1).getX() - mPointList.get(0).getX());
                    double y = (mPointList.get(1).getY() - mPointList.get(0).getY());
                    radius = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
                }

                getCircle(mPointList.get(0), radius);

                return super.onSingleTapConfirmed(e);
            }
        });
    }


    private void getCircle(Point point, double radius) {
        Point[] points = getPoints(point, radius);
        mPointCollection.clear();
        for (Point p : points) {
            mPointCollection.add(p);
        }

        Polygon polygon = new Polygon(mPointCollection);

        SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.YELLOW, 5);
        Graphic pointGraphic = new Graphic(point, simpleMarkerSymbol);
        mGraphicsOverlay.getGraphics().add(pointGraphic);

        SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.YELLOW, 2.0f);
        SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.parseColor("#66FF0000"), lineSymbol);

        Graphic graphic = new Graphic(polygon, simpleFillSymbol);
        mGraphicsOverlay.getGraphics().add(graphic);
    }

    /**
     * 通过中心点和半径计算得出圆形的边线点集合
     *
     * @param center
     * @param radius
     * @return
     */
    private static Point[] getPoints(Point center, double radius) {
        Point[] points = new Point[50];
        double sin;
        double cos;
        double x;
        double y;
        for (double i = 0; i < 50; i++) {
            sin = Math.sin(Math.PI * 2 * i / 50);
            cos = Math.cos(Math.PI * 2 * i / 50);
            x = center.getX() + radius * sin;
            y = center.getY() + radius * cos;
            points[(int) i] = new Point(x, y);
        }
        return points;
    }

}